package com.panopset.game;

import java.io.StringWriter;

public class DollarConverter {

    public String long2str(Long v) {
        if (v == null) {
            return "0.00";
        }
        boolean neg = false;
        if (v < 0) {
            neg = true;
        }
        v = Math.abs(v);
        StringWriter sw = new StringWriter();
        if (neg) {
            sw.append("-");
        }
        long dollars = 0;
        long cents = 0;
        if (v > 100) {
            dollars = v / 100;
            cents = v - (dollars * 100);
        } else {
            cents = v;
        }
        sw.append("" + dollars);
        sw.append(".");
        if (cents < 10) {
            sw.append("0");
        }
        sw.append("" + cents);
        return sw.toString();
    }

    public Long str2long(String s) {
        if (s == null || s.length() < 1 || s.equals(".")) {
            return 0L;
        }
        s = s.trim();
        boolean neg = false;
        if (s.indexOf("-") == 0) {
            neg = true;
            s = s.substring(1);
        }
        int d = s.indexOf(".");
        long rtn = 0;
        if (d > -1) {
            String dollars = s.substring(0, d);
            String pennies = s.substring(d + 1);
            if (dollars.length() > 0) {
                try {
                    rtn = Long.parseLong(dollars) * 100;
                } catch (NumberFormatException ex) {
                    return 0L;
                }
            }
            if (pennies.length() > 0) {
                try {
                    rtn = rtn + Long.parseLong(pennies);
                } catch (NumberFormatException ex) {
                    return 0L;
                }
            }
        } else {
            try {
                rtn = Long.parseLong(s) * 100;
            } catch (NumberFormatException ex) {
                return 0L;
            }
        }

        if (neg) {
            return rtn * -1;
        }
        return rtn;
    }

    public String int2str(Integer v) {
        return long2str(new Long(v));
    }

}
